package com.example.yilanchatserver.business.freechat.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.example.yilanchatserver.business.freechat.ErnieBotSubscriber;
import com.example.yilanchatserver.business.freechat.ErnieBotWebClient;
import com.example.yilanchatserver.business.freechat.service.ErnieBotService;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatDTO;
import com.example.yilanchatserver.business.freechat.service.dto.ErnieBotMessageDTO;
import com.example.yilanchatserver.business.freechat.service.dto.ErnieBotReqDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
@RequiredArgsConstructor
@Slf4j
public class ErnieBotServiceImpl implements ErnieBotService {

    private final ErnieBotWebClient ernieBotWebClient;

    @Override
    public Flux<String> send(FreeChatDTO chatDTO, String accessToken) {
        return Flux.create(emitter -> {
            ErnieBotSubscriber subscriber = new ErnieBotSubscriber(emitter);
            ErnieBotReqDTO reqDTO = new ErnieBotReqDTO();
            List<ErnieBotMessageDTO> messages = new ArrayList<>();
            List<Map<String, String>> talkList = chatDTO.getTalkList();
            if (CollectionUtil.isNotEmpty(talkList)) {
                for (Map<String, String> item : talkList) {
                    messages.add(new ErnieBotMessageDTO(item.get("talker"), item.get("text")));
                }
            }
            reqDTO.setMessages(messages);
            // 使用流式
            reqDTO.setStream(true);
            Flux<String> openAiResponse = ernieBotWebClient.getChatResponse(reqDTO, accessToken);
            openAiResponse.subscribe(subscriber);
            emitter.onDispose(subscriber);
        });
    }
}
